/*
 * Copyright (c) 2006 - 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>Project: app2022 - Sync2
 * <p>Powered by webrx On 2022-02-08 15:22:33
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class Sync2 {
    static volatile MySync2 ms = new MySync2();

    public static void main(String[] args) {
        new Thread(() -> {
            while (!ms.count()) ;
            System.out.println("已经有五个了");
        }, "监控线程").start();

        new Thread(() -> {
            for (int i = 1; i <= 20; i++) {
                ms.add();
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "t1").start();

    }
}

class MySync2 {
    private final List<String> list = new ArrayList<>();

    public void add() {
        list.add("add" + list.size());
        System.out.println(String.format("%d = %s", list.size(), list.get(list.size() - 1)));

    }

    public boolean count() {
        boolean f = false;
        if (list.size() >= 5) {
            System.out.println(Thread.currentThread().getName() + "线程启动");
            f = true;
        }
        return f;
    }
}
